﻿package cz.dadul.adventure.model
{
	import cz.dadul.adventure.model.Element;
	import flash.display.*;
	
	/**
	 * ...
	 * @author Dadul
	 */
	public class Layer extends Element
	{		
		public static const STANDARD_LAYER:int = 1;		
		
		protected var _standard:Sprite = new Sprite();
		// Layers array
		protected var _layers:Array = [];		
		protected var _scrollEnabled:Boolean;
		
		
		public function Layer(name:String,mc:MovieClip = null) 
		{
			super(name, mc);
		}
		
		public function addItem(item:Item, x:int = 0, y:int = 0, layerType:int = STANDARD_LAYER):Item{
			return addElement(item, x, y, layerType) as Item;
		}
		
		public function removeItem(item:Item):Boolean {
			return removeElement(item);
		}
		
		/**
		 * PROTECTED
		 */
		
		protected override function init():void {
			super.init();
			_scrollEnabled = true;
			// Initialize standard layer
			this._layers[STANDARD_LAYER] = _standard;	
			_standard.name = "Standardlayer";
			addChild(_standard);
		}
		
		protected function addElement(el:Element, x:int = 0, y:int = 0, layerType:int = STANDARD_LAYER):Element {
			var added:Boolean = false;
			var stackedEl :Item 
			//-------------------------------------
			// layer type check
			if (this._layers[layerType] == null) {
				throw new Error("Layer ["+this.name+"]: The layer type ["+layerType+"] is not supported!");	
			}			

			el.x = x;
			el.y = y;

			// Check depth (on already existing elements)
			for (var i:int = 0; i < this._layers[layerType].numChildren; i++) {
				stackedEl = this._layers[layerType].getChildAt(i);				
				if ( el.y < stackedEl.y ) {
					this._layers[layerType].addChildAt(el, i);
					added = true;
					break;
				}
			}
			// If the element has not been added yet
			if (!added) {
				this._layers[layerType].addChild(el);
			}

			return el;
		 }		
		 
		 protected function removeElement(el:Element):Boolean {
			 /*
			  * First parent - _layers
			  * Second layer - This layer itself
			  */ 
			 // Does the item belong to this layer?
			 if (el.parent.parent.name == this.name) {
				el.parent.removeChild(el); 
				return true;
			 } else {
				 return false;
			 }
		 }
		 
		 /**
		  * SETTERS / GETTERS
		  */
		 public function set scrollEnabled(b:Boolean):void {
			 _scrollEnabled = b;
		 }
		 public function get scrollEnabled():Boolean {
			 return _scrollEnabled;
		 }
		 
	}

}